//
//  NSObject+Tag.m
//  YanXiuWang
//
//  Created by 慧趣小歪 on 17/1/11.
//  Copyright © 2017年 小分队. All rights reserved.
//

#import "NSObject+Tag.h"
#import <objc/runtime.h>

@interface WeakItem : NSObject

@property (nonatomic, weak) NSObject *obj;

@end

@implementation WeakItem

- (void)dealloc {
    _obj.weakTag = nil;
}

@end

@implementation NSObject (Tag)

- (instancetype)then:(void(NS_NOESCAPE ^)(id obj))then{
    then(self);
    return self;
}


- (id)weakTag {
    return objc_getAssociatedObject(self, @selector(weakTag));
}

- (void)setWeakTag:(id)weakTag {
    objc_setAssociatedObject(self, @selector(weakTag), weakTag, OBJC_ASSOCIATION_ASSIGN);
    if (weakTag != nil) {
        WeakItem *item = objc_getAssociatedObject(weakTag, "weak.tag.item.auto.release") ?: [[WeakItem alloc] init];
        item.obj = self;
        objc_setAssociatedObject(weakTag, "weak.tag.item.auto.release", item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}


- (id)strongTag {
    return objc_getAssociatedObject(self, @selector(strongTag));
}

- (void)setStrongTag:(id)strongTag {
    objc_setAssociatedObject(self, @selector(strongTag), strongTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
